package gameuserlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/game"
	"navi-mumbai/common/key/gamekey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"

	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUidByOpenIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUidByOpenIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUidByOpenIdLogic {
	return &GetUidByOpenIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 根据openid查询uid
func (l *GetUidByOpenIdLogic) GetUidByOpenId(in *pb.GetUidByOpenIdReq) (*pb.GetUidByOpenIdResp, error) {
	defer utils.RecoverPanic()

	var err error
	var openId int64
	var uid int64
	openId, err = strconv.ParseInt(in.OpenId, 10, 64)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "openId error")
	}

	switch in.ProviderId {
	case gamekey.ProviderIdY9Y:
		var uo *game.UserOpenId1
		uo, err = l.svcCtx.UserOpenId1Model.FindOneByOpenId(l.ctx, openId)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
		uid = uo.Uid

	default:
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "provider id error")
	}

	return &pb.GetUidByOpenIdResp{Uid: uid}, nil
}
